package com.shushan.home;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.ActivityStackManager;
import com.shushan.base.BaseHomeFragment;
import com.shushan.base.Constants;
import com.shushan.discount.CouponExchangeActivity;
import com.shushan.discount.MyDiscountActivity;
import com.shushan.invitecode.InviteCalendarActivity;
import com.shushan.login.bean.ChildBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.pages.InviteForFreeUseActivity;
import com.shushan.pages.MyCollectionActivity;
import com.shushan.pages.MyStarActivity;
import com.shushan.pages.MyWrongTopicActivity;
import com.shushan.pages.OpenVipSpendActivity;
import com.shushan.pages.ScoreReceiveActivity;
import com.shushan.pages.SetActivity;
import com.shushan.pages.StarMallActivity;
import com.shushan.pages.UserServiceCenterActivity;
import com.shushan.permission.OpenUsageActivity;
import com.shushan.service.DialRTAService;
import com.shushan.setting.ParentSettingActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.ui.VerificationCodeView;
import com.shushan.util.DialogUtil;
import com.shushan.util.OnFingerSuccessListener;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.shushan.util.SystemUtils;
import com.shushan.util.ToolUtils;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @ClassName: MyHomeFagment
 * @Desciption: 首页我的界面
 * @author: yichaohua
 * @date: 2018-09-12
 */
public class MyHomeFragment extends BaseHomeFragment implements View.OnClickListener,VerificationCodeView.OnCodeFinishListener, OnFingerSuccessListener {

    private static final String TAG = "MyHomeFragment";

    private TextView tvChildName;
    private TextView tvLevelTerm;
    private RelativeLayout rlVipCenter;
    private RelativeLayout rlGiveLessons;
    private RelativeLayout rlMyStar;
    private RelativeLayout rlStarMall;
    private RelativeLayout rlMyCollection;
    private RelativeLayout rlMyWrongTopic;
    private RelativeLayout rlCouponExchange;
    private RelativeLayout rlMyCoupon;
    private RelativeLayout rlBackHome;
    private RelativeLayout rlUserServiceCenter;
    private RelativeLayout rlSet;
    private RelativeLayout scoreReceiveLayout;
    private LinearLayout llLevelTerm;
    private TextView tvStarNum;
    private TextView tvCollectCount;
    private TextView tvErrCount;
    private ImageView vipImageView;

    private BabyApplication babyApplication = BabyApplication.getInstance();
    private VerificationCodeView veriCodeView;
    private int dialogType = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_home,null);

        initView(view);

        getData();

        return view;
    }

    private void initView(View view){
        vipImageView = view.findViewById(R.id.my_home_vip_img);
        if(babyApplication.isUseVip()){
            vipImageView.setVisibility(View.VISIBLE);
        }else {
            vipImageView.setVisibility(View.GONE);
        }
        tvChildName = view.findViewById(R.id.tv_child_name);
        ChildBean childBean = babyApplication.getCurrentChildBean();
        if(childBean != null && !TextUtils.isEmpty(childBean.childName)){
            tvChildName.setText(childBean.childName);
        }

        tvLevelTerm = view.findViewById(R.id.tv_level_term);
        tvLevelTerm.setText(ToolUtils.getLevelTermText(babyApplication.getCurrentChildBean()));
        rlVipCenter = view.findViewById(R.id.rl_vip_center);
        rlVipCenter.setOnClickListener(this);
        rlGiveLessons = view.findViewById(R.id.rl_give_friend_lessons);
        rlGiveLessons.setOnClickListener(this);
        rlMyStar = view.findViewById(R.id.rl_my_star);
        rlMyStar.setOnClickListener(this);
        rlStarMall = view.findViewById(R.id.rl_star_mall);
        rlStarMall.setOnClickListener(this);
        rlMyCollection = view.findViewById(R.id.rl_my_collection);
        rlMyCollection.setOnClickListener(this);
        rlMyWrongTopic = view.findViewById(R.id.rl_my_wrong_topic);
        rlMyWrongTopic.setOnClickListener(this);
        rlCouponExchange = view.findViewById(R.id.rl_coupon_exchange);
        rlCouponExchange.setOnClickListener(this);
        rlMyCoupon = view.findViewById(R.id.rl_my_coupon);
        rlMyCoupon.setOnClickListener(this);
        rlBackHome = view.findViewById(R.id.rl_back_home);
        rlBackHome.setOnClickListener(this);
        rlUserServiceCenter = view.findViewById(R.id.rl_user_service_center);
        rlUserServiceCenter.setOnClickListener(this);
        rlSet = view.findViewById(R.id.rl_set);
        rlSet.setOnClickListener(this);
        llLevelTerm = view.findViewById(R.id.ll_level_term);
        llLevelTerm.setOnClickListener(this);
        scoreReceiveLayout = view.findViewById(R.id.my_home_score_layout);
        scoreReceiveLayout.setOnClickListener(this);
        tvStarNum = view.findViewById(R.id.tv_star_num);
        ChildBean currentChildBean = babyApplication.getCurrentChildBean();
        if(currentChildBean != null){
            tvStarNum.setText(currentChildBean.stars+"个");
        }

        tvCollectCount = view.findViewById(R.id.tv_collect_count);
        tvErrCount = view.findViewById(R.id.tv_err_count);
    }

    private void getData(){
        int childId = babyApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(getActivity(), UrlConst.BASE_URL).appendRegion(UrlConst.MY_CENTER);
        UrlParse paramParse = new UrlCommParse(getActivity())
                .putValue("child_id",childId);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {

                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        if(TextUtils.isEmpty(data)){
                            return;
                        }
                        try {
                            JSONObject obj = new JSONObject(data);
                            tvCollectCount.setText(obj.optInt("collect_count",0)+"题");
                            tvErrCount.setText(obj.optInt("error_count",0)+"题");
                            tvStarNum.setText(babyApplication.getCurrentChildBean().stars+"个");
                            tvLevelTerm.setText(ToolUtils.getLevelTermText(babyApplication.getCurrentChildBean()));
                            tvChildName.setText(babyApplication.getCurrentChildBean().childName);
                            if(babyApplication.isUseVip()){
                                vipImageView.setVisibility(View.VISIBLE);
                            }else {
                                vipImageView.setVisibility(View.GONE);
                            }
                        }catch (JSONException je){
                            je.printStackTrace();
                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rl_vip_center://会员中心
                startActivity(OpenVipSpendActivity.class);
                break;
            case R.id.rl_give_friend_lessons://赠送好友课程
                Intent intent1 = new Intent(getActivity(),InviteForFreeUseActivity.class);
                intent1.putExtra("hideTaste",true);
                startActivityAllow(intent1);
                break;
            case R.id.rl_my_star://我的学贝
                startActivity(MyStarActivity.class);
                break;
            case R.id.rl_star_mall://学贝商城
                startActivity(StarMallActivity.class);
                break;
            case R.id.rl_my_collection://我的收藏
                startActivity(MyCollectionActivity.class);
                break;
            case R.id.rl_my_wrong_topic://我的错题
                startActivity(MyWrongTopicActivity.class);
                break;
            case R.id.rl_coupon_exchange://优惠券兑换
                startActivity(CouponExchangeActivity.class);
                break;
            case R.id.rl_my_coupon://我的优惠券
                startActivity(MyDiscountActivity.class);
                break;
            case R.id.rl_back_home://返回桌面
                boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
                if(isChildControl){
                    dialogType = 2;
                    veriCodeView = DialogUtil.showInputParentPswDialog(getActivity(), this, this,this);
                }else {
                    Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_HOME);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                    startActivityAllow(intent);
                }
                break;
            case R.id.rl_user_service_center://客服中心
                startActivity(UserServiceCenterActivity.class);
                break;
            case R.id.rl_set://设置
                startActivity(SetActivity.class);
                break;
            case R.id.ll_level_term://年级
                dialogType = 1;
                veriCodeView = DialogUtil.showInputParentPswDialog(getActivity(), this, this,this);
                break;
            case R.id.btn_find_back_psw:
                DialogUtil.showForgetPswDialog(getActivity(),this);
                break;
            case R.id.btn_cancel:
                DialogUtil.dismissParentSetDialog();
                break;
            case R.id.iv_close_no_bg://忘记密码dialog：×
                DialogUtil.dismissDialog();
                break;
            case R.id.iv_client_phone_num://忘记密码dialog：客服电话
                DialCustom();
                break;
            case R.id.my_home_score_layout:
                startActivity(ScoreReceiveActivity.class);
                break;
            default:
                break;
        }
    }

    private void DialCustom() {
        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        if(isChildControl && !SystemUtils.checkUsagePermission(getActivity())){
            showNoUsageDialog();
            return;
        }

        try {
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Constants.CLIENT_PHONE_NUM));
            startActivityAllow(intent);
            DialogUtil.dismissDialog();
            DialogUtil.dismissParentSetDialog();
        }catch (SecurityException se){
            se.printStackTrace();
            showToast("没有打电话权限");
            return;
        }

        if(isChildControl){
            ActivityStackManager.getActivityStackManager().popAllActivity();
            Intent intent = new Intent(getActivity(),DialRTAService.class);
            intent.putExtra("allowPackName",Constants.ALLOW_DIAL_PACK_NAME);
            getActivity().startService(intent);
        }
    }

    private void showNoUsageDialog() {
        new CustomDialog.Builder(getActivity())
                .setTitle("温馨提示")
                .setMessage("发现您尚未开启“有权查看应用使用情况”，将导致无法返回首页，是否去设置？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivity(OpenUsageActivity.class);
                    }
                })
                .create().show();
    }

    @Override
    public void onComplete(String content) {
        if(StringTools.pswValide(content)){
            if(dialogType == 1){
                startActivityForResult(ParentSettingActivity.class);
            }else if(dialogType == 2){
                Intent intent= new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                startActivityAllow(intent);
            }

            DialogUtil.dismissParentSetDialog();
        }else{
            showToast("家长密码错误");
            if(veriCodeView != null){
                veriCodeView.clear();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.i(TAG,"requestCode=" + requestCode + " resultCode=" + resultCode);

        if(requestCode == 100){
            ChildBean childBean = babyApplication.getCurrentChildBean();
            if(childBean != null && !TextUtils.isEmpty(childBean.childName)){
                tvChildName.setText(childBean.childName);
                tvLevelTerm.setText(ToolUtils.getLevelTermText(childBean));
            }

            if(babyApplication.isUseVip()){
                vipImageView.setVisibility(View.VISIBLE);
            }else {
                vipImageView.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onFragmentChecked() {
        getData();
    }

    @Override
    public void onFragmentHided() {

    }

    @Override
    public void onFingerSuccess() {
        if(dialogType == 1){
            startActivityForResult(ParentSettingActivity.class);
        }else if(dialogType == 2){
            Intent intent= new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            startActivityAllow(intent);
        }

        DialogUtil.dismissParentSetDialog();
    }
}
